//
//  MTTableViewController.m
//  iMeituanHD
//
//  Created by 李 帅 on 12-2-29.
//  Copyright (c) 2012年 meituan. All rights reserved.
//

#import "MTTableViewController.h"

#import "DVSetting.h"
#import "CMCommonCategory.h"

@implementation MTTableViewController

- (void)dealloc {
    _tableView.delegate = nil;
    _tableView.dataSource = nil;
}
- (id)initWithStyle:(UITableViewStyle)tableStyle {
    self = [super init];
    self.tableStyle = tableStyle;
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self tableView];
}
- (void)viewDidUnload {
    self.tableView = nil;
    [super viewDidUnload];
}

- (void)setItems:(NSMutableArray *)items {
    _items = items;
    [self.tableView reloadData];
}

- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-20) style:self.tableStyle];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.backgroundView = nil;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_sections) {
        return _items.count;
    }
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_sections) {
        NSArray *aSection = [_items objectAtIndex:section];
        return aSection.count;
    }
    return _items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MTTableItem *item = nil;
    if (_sections) {
        item = [[_items objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }else {
        item = [_items objectAtIndex:indexPath.row];
    }
    MTTableCell *cell = [tableView dequeueReusableCellWithIdentifier:item.cellClassName];
    if (cell == nil) {
        cell = [[NSClassFromString(item.cellClassName) alloc] init];
    }
    [cell setItem:item];
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (_sections.count > section) {
        return [_sections objectAtIndex:section];
    }
    return nil;
}
#pragma mark -
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MTTableItem *item = nil;
    if (_sections) {
        item = [[_items objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }else {
        item = [_items objectAtIndex:indexPath.row];
    }
    return [item cellHeightWithWidth:tableView.width];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MTTableItem *item = nil;
    if (_sections) {
        item = [[_items objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }else {
        item = [_items objectAtIndex:indexPath.row];
    }
    
    UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
    if (item.target && item.selectAction && [item.target respondsToSelector:item.selectAction]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [item.target performSelector:item.selectAction withObject:item withObject:selectedCell];
#pragma clang diagnostic pop
    }else if (_delegate && [_delegate respondsToSelector:@selector(tableController:didSelectRowAtIndexPath:selectedItem:forCell:)]) {
        [_delegate tableController:self didSelectRowAtIndexPath:indexPath selectedItem:item forCell:selectedCell];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return YES;
}
@end




////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation MTTableItem

+ (id)item {
    return [[self alloc] init];
}
- (id)init {
    self = [super init];
    if (self) {
        _cellHeight = 44;
    }
    return self;
}
- (void)setSelectAction:(SEL)selectAction target:(id)target {
    _target = target;
    _selectAction = selectAction;
}
- (int)cellHeightWithWidth:(int)width {
    return self.cellHeight;
}
- (NSString *)cellClassName {
    if (_cellClassName == nil) {
        _cellClassName = [[[[self class] description] stringByReplacingOccurrencesOfString:@"Item" withString:@"Cell"] copy];
    }
    return _cellClassName;
}
@end

@implementation MTTableCell

@synthesize item = _item;
- (void)setItem:(MTTableItem *)item {
    _item = item;
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    [super setHighlighted:highlighted animated:animated];
    
    for (UILabel *label in self.contentView.subviews) {
        if ([label isKindOfClass:[UILabel class]]) {
            label.highlighted = highlighted;
        }
    }
    for (UILabel *label in self.subviews) {
        if ([label isKindOfClass:[UILabel class]]) {
            label.highlighted = highlighted;
        }
    }

    self.textLabel.highlighted = highlighted;
    self.detailTextLabel.highlighted = highlighted;
}
- (id)initWithStyle:(UITableViewCellStyle)style {
    self = [self initWithStyle:style reuseIdentifier:[[self class] description]];
    return self;
}
- (id)init {
    return [self initWithStyle:UITableViewCellStyleDefault];
}
@end

////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation MTTableMenuItem


@end

@implementation MTTableMenuCell

-(id)init {
    self = [super init];
    if (self) {
        _canBecomeFirstResponder = NO;
    }
    return self;
}

//下面是关于弹出菜单的功能，使用时在子类setItem里调用 addLongPressMenuWithName 添加菜单，然后调用finishLongPressMenuConfig即可。
-(void)beginLongPressMenuConfig {/////添加该方法是为了cell复用时重复调用setItem方法时清空以前菜单项
    if (_menuActionNames == nil) {
        _menuActionNames = [NSMutableArray array];
    }
    [_menuActionNames removeAllObjects];
    if (_menuItems == nil) {
        _menuItems = [NSMutableArray array];
    }
    [_menuItems removeAllObjects];
    _canBecomeFirstResponder = YES;
}
- (void)addLongPressMenuWithName:(NSString*)menuName actionName:(NSString*)actionName {
    [_menuActionNames addObject:actionName];
    [_menuItems addObject:[[UIMenuItem alloc] initWithTitle:menuName action:NSSelectorFromString(actionName)]];
}
- (void)finishLongPressMenuConfig {
    [self registLongPressGestureRecongnizer];
}
- (void)registLongPressGestureRecongnizer {
    UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress)];
    longPressGR.minimumPressDuration = 1;
    [self addGestureRecognizer:longPressGR];
}
- (void)handleLongPress {
    UIMenuController *menu = [UIMenuController sharedMenuController];
    if (_menuActionNames.count > 0 && menu.isMenuVisible == NO) {
        [self becomeFirstResponder];
        menu.menuItems = _menuItems;
        [menu setTargetRect:self.frame inView:self.superview];
        [menu setMenuVisible:YES animated:YES];
    }
}
//实现弹出menu，该view必须复写的两个方法
- (BOOL)canBecomeFirstResponder {
    return _canBecomeFirstResponder;
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    NSString *actionName;
    for (actionName in _menuActionNames) {
        if (action == NSSelectorFromString(actionName)) {
            return YES;
        }
    }
    return NO;
}

@end
////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation MTTableSingleTitleItem

@synthesize title = _title;
@synthesize font = _font;
@synthesize textColor = _textColor;
@synthesize textAlignment = _textAlignment;
- (id)initWithTitle:(NSString *)title {
    self = [super init];
    if (self) {
        self.title = title;
    }
    
    return self;
}
+ (id)itemWithTitle:(NSString *)title {
    return [self itemWithTitle:title font:Font(14)];
}
+ (id)itemWithTitle:(NSString *)title font:(UIFont *)font {
    MTTableSingleTitleItem *item = [[self alloc] initWithTitle:title];
    item.font = font;
    return item;
}
+ (id)itemWithTitle:(NSString *)title font:(UIFont *)font textColor:(UIColor *)textColor {
    MTTableSingleTitleItem *item = [self itemWithTitle:title font:font];
    item.textColor = textColor;
    return item;
}
- (int)cellHeightWithWidth:(int)width {
    if (_cellHeight == 0) {
        _cellHeight = [_title heightWithFont:_font limitByWidth:width];
    }
    return _cellHeight;
}
@end

@implementation MTTableSingleTitleCell

- (id)init {
    self = [super initWithStyle:UITableViewCellStyleDefault];
    return self;
}
- (void)setItem:(MTTableItem *)item {
    super.item = item;
    self.textLabel.numberOfLines = 0;
    
    MTTableSingleTitleItem *singleTitleItem = (MTTableSingleTitleItem *)item;
    self.textLabel.text = singleTitleItem.title;
    self.textLabel.font = singleTitleItem.font;
    self.textLabel.textAlignment = singleTitleItem.textAlignment;
    if (singleTitleItem.textColor) {
        self.textLabel.textColor = singleTitleItem.textColor;
    }
    
    [self setNeedsDisplay];
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    [super setHighlighted:highlighted animated:animated];
    
    self.textLabel.highlighted = NO;
}
@end

////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation MTTableControlItem

@synthesize title = _title;
@synthesize control = _control;
- (id)initWithTitle:(NSString *)title control:(UIControl *)control {
    self = [super init];
    if (self) {
        _title = [title copy];
        _control = control;
    }
    return self;
}

@end

@implementation MTTableControlCell

- (id)init {
    self = [super initWithStyle:UITableViewCellStyleDefault];
    return self;
}
- (void)setItem:(MTTableItem *)item {
    super.item = item;
    MTTableControlItem *controlItem = (MTTableControlItem *)item;
    self.textLabel.text = controlItem.title;
    if ([self viewWithTag:100]) {
        [[self viewWithTag:100] removeFromSuperview];
    } 
    controlItem.control.tag = 100;
    [self.contentView addSubview:controlItem.control];
}
- (void)layoutSubviews {
    [super layoutSubviews];
    UIView *control = [self viewWithTag:100];
    control.right = self.contentView.width - 15;
    control.top = 10;
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    [super setHighlighted:highlighted animated:animated];
    
    self.textLabel.highlighted = highlighted;
}
@end

////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation MTTableDetailItem

@synthesize icon = _icon;
@synthesize title = _title;
@synthesize detail = _detail;
@synthesize accessIcon = _accessIcon;
- (id)initWithTitle:(NSString *)title detail:(NSString *)detail {
    return [self initWithIcon:nil title:title detail:detail accessIcon:nil];
}
- (id)initWithIcon:(UIImage *)icon title:(NSString *)title detail:(NSString *)detail accessIcon:(UIImage *)accessIcon {
    self = [super init];
    if (self) {
        self.icon = icon;
        self.title = title;
        self.detail = detail;
        self.accessIcon = accessIcon;
    }
    return self;
}

@end

@implementation MTTableDetailCell
@synthesize accessView = _accessView;
- (id)init {
    return [super initWithStyle:UITableViewCellStyleValue1];
}
- (void)setItem:(MTTableItem *)item {
    super.item = item;
    MTTableDetailItem *detailItem = (MTTableDetailItem *)item;

    self.imageView.image = detailItem.icon;
    self.textLabel.text = detailItem.title;
    self.textLabel.backgroundColor = [UIColor clearColor];
    self.detailTextLabel.text = detailItem.detail;
    if (detailItem.accessIcon) {
        self.accessView.image = detailItem.accessIcon;
    }else {
        [_accessView removeFromSuperview];
        self.accessView = nil;
    }
}
- (void)layoutSubviews {
    [super layoutSubviews];
    MTTableDetailItem *detailItem = (MTTableDetailItem *)self.item;
    if (detailItem.accessIcon) {
        self.accessView.image = detailItem.accessIcon;
        self.accessView.bounds = CGRectMake(0, 0, detailItem.accessIcon.size.width, detailItem.accessIcon.size.height);
        self.accessView.center = CGPointMake(self.width-20-self.accessView.width/2, self.height/2);
        self.detailTextLabel.right = self.accessView.left-5;
    }
}
- (UIImageView *)accessView {
    if (_accessView == nil) {
        _accessView = [[UIImageView alloc] init];
        [self.contentView addSubview:_accessView];
    }
    return _accessView;
}
- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated{
    [super setHighlighted:highlighted animated:animated];
    
    self.textLabel.highlighted = highlighted;
    self.detailTextLabel.highlighted = highlighted;
}
@end


////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation MTTableMoreItem

@synthesize moreText = _moreText;
- (id)initWithText:(NSString *)moreText {
    self = [super init];
    if (self) {
        self.moreText = moreText;
    }
    return self;
}
@end

@implementation MTTableMoreCell

@synthesize moreTextLabel = _moreTextLabel;
@synthesize loading = _loading;
@synthesize activeView = _activeView;


- (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {
    [super setHighlighted:highlighted animated:animated];
    if (highlighted) {
        UIView *blueView = [[UIView alloc] init];
        blueView.backgroundColor = RGBCOLOR(65, 158, 198);
        self.backgroundView = blueView;
    }else {
        self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tableCellBack.png"]];
    }
}

- (void)setItem:(MTTableMoreItem *)item {
    super.item = item;
    self.loading = NO;
}
- (void)setLoading:(BOOL)loading {
    _loading = loading;
    if (_loading) {
        [self addSubview:self.activeView];
        [_activeView startAnimating];
        
        _moreTextLabel.text = @"加载中...";
    }else {
        [_activeView removeFromSuperview];
        self.activeView = nil;
        NSString *moreText = ((MTTableMoreItem *)_item).moreText;
        self.moreTextLabel.text = moreText?moreText:@"点击加载更多";
    }
}
- (UILabel *)moreTextLabel {
    if (_moreTextLabel == nil) {
        _moreTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, self.item.cellHeight)];
        _moreTextLabel.font = Font(13);
        _moreTextLabel.textAlignment = NSTextAlignmentCenter;
        _moreTextLabel.backgroundColor = [UIColor clearColor];
        _moreTextLabel.numberOfLines = 0;
        _moreTextLabel.highlightedTextColor = [UIColor whiteColor];
        [self addSubview:_moreTextLabel];
    }
    return _moreTextLabel;
}
- (UIActivityIndicatorView *)activeView {
    if (_activeView == nil) {
        _activeView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activeView.frame = CGRectMake(10, (self.height-15)/2, 15, 15);
    }
    return _activeView;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    _moreTextLabel.frame = CGRectMake(0, 0, 320, self.item.cellHeight);
    _activeView.frame = CGRectMake(10, (self.height-15)/2, 15, 15);
}
@end

////////////////////////////////////////////////////////////////////////////////////////////////////
@implementation MTTableRadioItem

- (NSString *)groupName {
    if (_groupName == nil) {
        _groupName = [[[self class] description] copy];
    }
    return _groupName;
}
@end

@implementation MTTableRadioCell

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)setItem:(MTTableRadioItem *)item {
    super.item = item;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusNeedChangeToUnSelected:) name:item.groupName object:nil];
    [self setRadioSelected:item.isSelected];
}
- (void)setRadioSelected:(BOOL)isSelected {
    MTTableRadioItem *item = (MTTableRadioItem *)self.item;
    item.isSelected = isSelected;
    if (isSelected) {
        [[NSNotificationCenter defaultCenter] postNotificationName:item.groupName object:self];
    }
}
- (void)statusNeedChangeToUnSelected:(NSNotification *)notification {
    if (notification.object != self) {
        [self setRadioSelected:NO];
    }
}
@end